import React, { Component } from 'react';
import _ from 'lodash';
import moment from 'moment';
import { Text, View } from 'react-native';
import styles from '../styles';
import { parseErrors, formStore } from '../..'
import StatusIcon from '../../statusIcon';
import SelectValue from '../selectValue';

export default class DateSelecter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: props.initialValue || '',
    };
  }
  componentWillReceiveProps(next) {
    if ((next.value !== this.props.value)) {
      this.setState({
        value: next.value
      }, () => {
        if (_.isFunction(this.props.afterChange)) {
          this.props.afterChange(next.value)
        }
      })
    }
  }
  onChange = value => {
    this.props.onChange(value);
  };
  activeDate = () => {
    formStore.activeDateIOS({
      key: this.props.fieldKey,
      value: this.props.initialValue,
      mode: this.props.mode,
      minDate: this.props.minDate,
      maxDate: this.props.maxDate,
    })
  }
  format = dateString => {
    if(dateString){
      switch(this.props.mode) {
        case 'time':{
          return moment(dateString).format('HH:mm:ss');
        }
        case 'datetime':
        case 'dateTime':
        {
          return moment(dateString).format('YYYY-MM-DD HH:mm');
        }
        case 'date':{
          return moment(dateString).format('YYYY-MM-DD');
        }
      }
    }
  }
  render() {
    return (
      <View style={styles.wrap}>
        <View style={styles.label}>
          <Text style={this.props.error && styles.errorLabel}>{this.props.label}</Text>
        </View>
        <View style={styles.value}>
          <SelectValue
            onPress={this.activeDate}
            value={this.format(this.state.value)}
            placeholder={this.props.placeholder}
          />
        </View>
        {this.props.error ? <StatusIcon type="error" msg={parseErrors(this.props.error)} /> : null}
      </View>
    );
  }
}